<?php
namespace App\Admin\Controllers\System;

use App\Admin\Controllers\Controller;
use Illuminate\Http\Request;
use App\Admin\Models\User;

use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Database\Query\Builder;

use App\Admin\Actions\DataTable;
use App\Admin\Actions\Create;
use App\Admin\Actions\Update;
use App\Admin\Actions\Delete;

use App\Admin\Requests\System\UserCreateRequest;
use App\Admin\Requests\System\UserUpdateRequest;

class UserController extends Controller
{
	use DataTable, Create, Update, Delete;

	public function modelName()
	{
		return User::class;
	}

	public function dataTable($setter)
	{
		$setter->validate(function($request){
			return $request->validate([
				'username' => 'nullable|string',
				'nickname' => 'nullable|string',
				'mobile'   => 'nullable|integer',
				'email'    => 'nullable|email|max:50',
				'role_id'  => 'nullable|integer',
				'name'     => 'nullable|string|max:50',
				'contact'  => 'nullable|string|max:50',
			]);
		});

		$setter->search(function($query, $validated){
			if( !empty($validated['username']) ){
				$query->where('username', $validated['username']);
			}
			if( !empty($validated['nickname']) ){
				$query->where('nickname', $validated['nickname']);
			}
			if( !empty($validated['mobile']) ){
				$query->where('mobile', $validated['mobile']);
			}
			if( !empty($validated['email']) ){
				$query->where('email', $validated['email']);
			}

			// 联系方式搜索 手机号或邮箱
			if( !empty($validated['contact']) ){
				if (filter_var($validated['contact'], FILTER_VALIDATE_EMAIL)) {
					// 完整邮箱搜索
					$query->where('email', $validated['contact']);

				} elseif( (filter_var($validated['contact'], FILTER_VALIDATE_INT) !== false) && strlen($validated['contact']) == 11 ) {
					// 11位手机号搜索 这里也有11位数字开头的邮箱情况存在 过于小众不管
					$query->where('mobile', $validated['contact']);

				} else {
					// 既不是完整邮箱也不是11位数字 模糊搜索
					$query->where('email', 'like', "%{$validated['contact']}%");
					$query->orWhere('mobile', 'like', "%{$validated['contact']}%");
				}
			}


	        if( !empty($validated['role_id']) ){
		        $query->join('system_user_role', 'user_id', 'system_user.id');
		        $query->where('system_user_role.role_id', $validated['role_id']);
		        $query->select(['system_user.*']);
	        }
		});

		$setter->after(function($models){
			$models->append('role_ids')->makeHidden('roles');
		});
	}


	public function store(UserCreateRequest $request)
	{
		try {
			$validated = $request->validated();

			$model = User::create($validated);
			$model?->roles()?->attach($validated['role_ids']);

			return [
				'code' => 0, 
				'data' => $model
			];


		} catch (\Exception $e) {
			return ['code'=>1, 'm'=>$e->getMessage()];
		}
	}


	public function update(UserUpdateRequest $request, $id)
	{
		try {
			$validated = $request->validated();

			$model = User::findOrFail($id);
			$model->fill($validated);
			$isDirty = $model->isDirty();
			if( $isDirty ){
				$model->save();
			}
			
			if( isset($validated['role_ids']) ){
				$model?->roles()?->sync($validated['role_ids']);
			}

			return [
				'code' => 0, 
				'data' => [
					'isDirty' => $isDirty,
					'data' => $model,
				],
			];


		} catch (\Exception $e) {
			return ['code'=>1, 'm'=>$e->getMessage()];
		}
	}


	public function actionDelete($setter)
	{
		$setter->handle(function($eloquent){
			if( !($eloquent instanceof \Illuminate\Database\Eloquent\Model) ){
				if( $eloquent->count() > 1 ){
					abort(500, '禁止批量删除');
				}else{
					$eloquent = $eloquent[0];
				}
			}

			if( $eloquent->id == 1 ){
				abort(500, '禁止删除超管');
			}

			// 删除对应的role
			DB::table('system_user_role')->where('user_id', $eloquent->id)->delete();
			$eloquent->delete();
		});
	}
}
